package ua.org.nuos.sdms.clientgui.client.handlers;

import ua.org.nuos.sdms.clientgui.client.context.Messages;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.DetachUserFromGroupEvent;
import ua.org.nuos.sdms.clientgui.client.events.ErrorMessageEvent;
import ua.org.nuos.sdms.clientgui.client.events.ShowDialogMessageEvent;
import ua.org.nuos.sdms.clientgui.client.listeners.DetachUserFromGroupListener;
import ua.org.nuos.sdms.clientgui.client.listeners.DialogResultHandler;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 10.04.12
 * Time: 17:47
 * To change this template use File | Settings | File Templates.
 */
public class DetachUserFromGroupHandler implements DetachUserFromGroupListener {
    @Override
    public void detach(DetachUserFromGroupEvent event) {
        ShowDialogMessageEvent e = new ShowDialogMessageEvent(getDialogResultHandler(event), "Внимание!", "<b>Изгнать из группы?</b>");
        AppProxy.getInstance().getController(GlobalBoard.ID).fire(e);
    }

    private DialogResultHandler getDialogResultHandler(final DetachUserFromGroupEvent event) {
        return new DialogResultHandler() {
            @Override
            public void dialogResultProcess(boolean accepted) {
                if (accepted) {
                    long userId = event.getUserId();
                    Group group = AppProxy.getInstance().getModelLocator().getGroup();
                    if (group != null) {
                        try {
                            AppProxy.getInstance().getServiceLocator().getClientBean().detachUserFromGroup(userId, group.getId());
                        } catch (Exception ex) {
                            Logger.getAnonymousLogger().log(Level.WARNING, "Detach user from group error", ex);
                            AppProxy.getInstance().getControllerLocator().getController(GlobalBoard.ID).fire(new ErrorMessageEvent(Messages.ACTION_ERROR));
                        } finally {
                            AppProxy.getInstance().getModelLocator().getGroupContainer().fireListeners();
                        }
                    }
                }
            }
        };
    }
}
